<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>考试成绩详情</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          @click="goBack">
          返回列表
        </el-button>
      </div>
      
      <div v-loading="loading">
        <!-- 基本信息 -->
        <div class="result-header">
          <h2 class="result-title">{{ result.examTitle }}</h2>
          <div class="result-score">
            <span class="score-value">{{ result.score }}</span>
            <span class="score-total">/{{ result.totalScore }}</span>
            <span class="score-rate">（{{ calculateScoreRate(result.score, result.totalScore) }}%）</span>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <div class="result-info">
          <div class="info-row">
            <div class="info-item">
              <span class="label">学生姓名：</span>
              <span>{{ result.studentName }}</span>
            </div>
            <div class="info-item">
              <span class="label">学号：</span>
              <span>{{ result.studentId }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">学校：</span>
              <span>{{ result.schoolName }}</span>
            </div>
            <div class="info-item">
              <span class="label">班级：</span>
              <span>{{ result.className }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">学科：</span>
              <span>{{ result.subjectName }}</span>
            </div>
            <div class="info-item">
              <span class="label">教育阶段：</span>
              <span>{{ result.educationLevelName }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">开始时间：</span>
              <span>{{ formatDateTime(result.startTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">提交时间：</span>
              <span>{{ formatDateTime(result.submitTime) }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">用时：</span>
              <span>{{ calculateDuration(result.startTime, result.submitTime) }}</span>
            </div>
            <div class="info-item">
              <span class="label">试卷时长：</span>
              <span>{{ result.duration }} 分钟</span>
            </div>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <!-- 答题详情 -->
        <div class="answer-section">
          <h3>答题详情</h3>
          
          <div v-for="(section, sectionIndex) in result.sections" :key="sectionIndex" class="question-section">
            <h4 class="section-title">
              {{ sectionIndex + 1 }}. {{ section.name }}
              <span class="section-score">（{{ section.obtainedScore }}/{{ section.totalScore }}分）</span>
            </h4>
            
            <div v-for="(question, questionIndex) in section.questions" :key="questionIndex" class="question-item">
              <div class="question-header">
                <div class="question-title">
                  <span class="question-index">{{ sectionIndex + 1 }}-{{ questionIndex + 1 }}.</span>
                  <span v-html="question.content"></span>
                  <span class="question-score">（{{ question.obtainedScore }}/{{ question.score }}分）</span>
                </div>
                <div class="question-status">
                  <el-tag :type="question.isCorrect ? 'success' : 'danger'" size="small">
                    {{ question.isCorrect ? '正确' : '错误' }}
                  </el-tag>
                </div>
              </div>
              
              <!-- 选择题选项 -->
              <div v-if="question.type === 1 || question.type === 2" class="question-options">
                <div 
                  v-for="(option, optionIndex) in question.options" 
                  :key="optionIndex"
                  :class="[
                    'option-item',
                    isOptionSelected(question.studentAnswer, option.key) ? 'option-selected' : '',
                    isCorrectOption(question, option.key) ? 'option-correct' : '',
                    isWrongOption(question, option.key) ? 'option-wrong' : ''
                  ]"
                >
                  <span class="option-key">{{ option.key }}.</span>
                  <span class="option-content" v-html="option.content"></span>
                </div>
              </div>
              
              <!-- 判断题答案 -->
              <div v-if="question.type === 3" class="question-judge">
                <div 
                  :class="[
                    'judge-item',
                    question.studentAnswer === 'true' ? 'option-selected' : '',
                    question.studentAnswer === 'true' && question.answer === 'true' ? 'option-correct' : '',
                    question.studentAnswer === 'true' && question.answer !== 'true' ? 'option-wrong' : ''
                  ]"
                >
                  <span class="judge-key">√</span>
                  <span class="judge-text">正确</span>
                </div>
                <div 
                  :class="[
                    'judge-item',
                    question.studentAnswer === 'false' ? 'option-selected' : '',
                    question.studentAnswer === 'false' && question.answer === 'false' ? 'option-correct' : '',
                    question.studentAnswer === 'false' && question.answer !== 'false' ? 'option-wrong' : ''
                  ]"
                >
                  <span class="judge-key">×</span>
                  <span class="judge-text">错误</span>
                </div>
              </div>
              
              <!-- 填空题答案 -->
              <div v-if="question.type === 4" class="question-fill">
                <div class="fill-answers">
                  <div v-for="(blank, blankIndex) in question.blanks" :key="blankIndex" class="fill-item">
                    <div class="fill-label">空{{ blankIndex + 1 }}:</div>
                    <div class="fill-content">
                      <div class="student-answer">
                        <span class="answer-label">学生答案：</span>
                        <span 
                          :class="[
                            'answer-text',
                            isBlankCorrect(question, blankIndex) ? 'text-correct' : 'text-wrong'
                          ]"
                        >{{ getStudentBlankAnswer(question, blankIndex) }}</span>
                      </div>
                      <div class="correct-answer">
                        <span class="answer-label">正确答案：</span>
                        <span class="answer-text">{{ blank.answer }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 简答题答案 -->
              <div v-if="question.type === 5" class="question-essay">
                <div class="essay-answer">
                  <div class="student-answer">
                    <div class="answer-label">学生答案：</div>
                    <div class="answer-content" v-html="question.studentAnswer || '未作答'"></div>
                  </div>
                  <div class="correct-answer">
                    <div class="answer-label">参考答案：</div>
                    <div class="answer-content" v-html="question.answer"></div>
                  </div>
                  <div class="teacher-comment" v-if="question.comment">
                    <div class="comment-label">教师评语：</div>
                    <div class="comment-content">{{ question.comment }}</div>
                  </div>
                </div>
              </div>
              
              <div class="question-analysis" v-if="question.analysis">
                <div class="analysis-label">解析：</div>
                <div class="analysis-content" v-html="question.analysis"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getExamResultDetail } from '@/api/exam';

export default {
  name: 'ExamResultDetail',
  data() {
    return {
      loading: false,
      result: {
        id: null,
        examId: null,
        examTitle: '',
        studentId: '',
        studentName: '',
        schoolId: null,
        schoolName: '',
        className: '',
        subjectId: null,
        subjectName: '',
        educationLevel: null,
        educationLevelName: '',
        paperId: null,
        paperTitle: '',
        startTime: '',
        submitTime: '',
        duration: 0,
        score: 0,
        totalScore: 0,
        sections: []
      }
    };
  },
  created() {
    this.getResultDetail();
  },
  methods: {
    // 获取考试结果详情
    getResultDetail() {
      this.loading = true;
      const resultId = this.$route.params.id;
      if (!resultId) {
        this.$message.error('结果ID不能为空');
        this.goBack();
        return;
      }
      
      getExamResultDetail(resultId).then(response => {
        this.result = response.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取考试结果详情失败');
        this.goBack();
      });
    },
    // 计算得分率
    calculateScoreRate(score, totalScore) {
      if (!totalScore) return 0;
      return Math.round((score / totalScore) * 100);
    },
    // 计算考试用时
    calculateDuration(startTime, submitTime) {
      if (!startTime || !submitTime) return '未知';
      
      const start = new Date(startTime);
      const end = new Date(submitTime);
      const diff = (end - start) / 1000 / 60; // 分钟
      
      if (diff < 60) {
        return Math.round(diff) + ' 分钟';
      } else {
        const hours = Math.floor(diff / 60);
        const minutes = Math.round(diff % 60);
        return hours + ' 小时 ' + minutes + ' 分钟';
      }
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 判断选项是否被选中
    isOptionSelected(studentAnswer, optionKey) {
      if (!studentAnswer) return false;
      
      // 单选题
      if (typeof studentAnswer === 'string') {
        return studentAnswer === optionKey;
      }
      
      // 多选题
      if (Array.isArray(studentAnswer)) {
        return studentAnswer.includes(optionKey);
      }
      
      return false;
    },
    // 判断是否为正确选项
    isCorrectOption(question, optionKey) {
      if (!question.answer) return false;
      
      // 单选题
      if (typeof question.answer === 'string') {
        return question.answer === optionKey && this.isOptionSelected(question.studentAnswer, optionKey);
      }
      
      // 多选题
      if (Array.isArray(question.answer)) {
        return question.answer.includes(optionKey) && this.isOptionSelected(question.studentAnswer, optionKey);
      }
      
      return false;
    },
    // 判断是否为错误选项
    isWrongOption(question, optionKey) {
      if (!question.answer || !question.studentAnswer) return false;
      
      // 单选题
      if (typeof question.studentAnswer === 'string') {
        return question.studentAnswer === optionKey && question.answer !== optionKey;
      }
      
      // 多选题
      if (Array.isArray(question.studentAnswer)) {
        return question.studentAnswer.includes(optionKey) && !question.answer.includes(optionKey);
      }
      
      return false;
    },
    // 判断填空题空格是否正确
    isBlankCorrect(question, blankIndex) {
      if (!question.blanks || !question.blanks[blankIndex]) return false;
      
      const studentAnswers = question.studentAnswer ? question.studentAnswer.split('|') : [];
      const correctAnswer = question.blanks[blankIndex].answer;
      
      if (studentAnswers[blankIndex]) {
        // 如果有多个可能的答案，用逗号分隔
        const possibleAnswers = correctAnswer.split('，');
        return possibleAnswers.some(answer => answer.trim() === studentAnswers[blankIndex].trim());
      }
      
      return false;
    },
    // 获取学生填空题答案
    getStudentBlankAnswer(question, blankIndex) {
      if (!question.studentAnswer) return '未作答';
      
      const studentAnswers = question.studentAnswer.split('|');
      return studentAnswers[blankIndex] || '未作答';
    },
    // 返回列表
    goBack() {
      // 如果是从考试结果列表页面进入，返回结果列表
      if (this.$route.query.from === 'results') {
        this.$router.push('/exams/results');
      } else {
        // 否则返回考试详情页
        this.$router.push(`/exam/detail/${this.result.examId}`);
      }
    }
  }
};
</script>

<style scoped>
.result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.result-title {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.result-score {
  font-size: 20px;
}

.score-value {
  font-size: 28px;
  font-weight: bold;
  color: #f56c6c;
}

.score-total {
  font-size: 18px;
  color: #606266;
}

.score-rate {
  margin-left: 10px;
  font-size: 16px;
  color: #909399;
}

.result-info {
  margin: 20px 0;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  flex: 1;
  display: flex;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
  min-width: 80px;
}

.answer-section {
  margin-top: 20px;
}

.question-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.section-score {
  font-size: 16px;
  color: #409eff;
  margin-left: 10px;
}

.question-item {
  margin-bottom: 25px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.question-title {
  flex: 1;
  line-height: 1.5;
}

.question-index {
  font-weight: bold;
  margin-right: 5px;
}

.question-score {
  font-size: 14px;
  color: #409eff;
  margin-left: 10px;
}

.question-options, .question-judge {
  margin-left: 25px;
  margin-bottom: 15px;
}

.option-item, .judge-item {
  padding: 8px 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.option-key, .judge-key {
  font-weight: bold;
  margin-right: 10px;
  min-width: 20px;
}

.option-selected {
  background-color: #f0f9eb;
}

.option-correct {
  border: 1px solid #67c23a;
}

.option-wrong {
  border: 1px solid #f56c6c;
}

.question-fill {
  margin-left: 25px;
  margin-bottom: 15px;
}

.fill-item {
  display: flex;
  margin-bottom: 15px;
}

.fill-label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 40px;
}

.fill-content {
  flex: 1;
}

.student-answer, .correct-answer {
  margin-bottom: 8px;
}

.answer-label, .analysis-label, .comment-label {
  font-weight: bold;
  color: #606266;
  margin-bottom: 5px;
}

.text-correct {
  color: #67c23a;
}

.text-wrong {
  color: #f56c6c;
}

.question-essay {
  margin-left: 25px;
  margin-bottom: 15px;
}

.essay-answer {
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.answer-content, .analysis-content, .comment-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 10px;
  white-space: pre-line;
}

.question-analysis {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #ebeef5;
}
</style> 